import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:sph_shipper/AppConfig/Config.dart';

import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'AddGoodsFirst.dart';
import 'SourceDetails.dart';

class FrequentlyShippedSources extends StatefulWidget {
  const FrequentlyShippedSources({super.key});

  @override
  State<FrequentlyShippedSources> createState() => _FrequentlyShippedSourcesState();
}

class _FrequentlyShippedSourcesState extends State<FrequentlyShippedSources> {
  List orderID =["111111","222222","333333",];
  List dataList=[];
  ScrollController _scrollController = ScrollController();
  bool _isLoading = false;
  bool isLoading =false;
  int pageNum=1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getGoodsHistory(1);
    _scrollController.addListener(() {
      // 检查是否滚动到底部
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        // 滚动到底部时加载更多数据

        _loadMoreData();
      }
    });
  }
  Future<void> _loadMoreData() async {
    // // 避免重复加载
    // if (_isLoading) {
    //   return;
    // }
    //
    // // 开始加载更多数据
    // setState(() {
    //   _isLoading = true;
    // });
    //
    // // 模拟异步加载更多数据，比如从网络获取数据
    // await Future.delayed(Duration(seconds: 2));

    // 加载更多数据后更新列表
    setState(() {
      getGoodsHistory(1);
      _isLoading = false;
    });
  }

  void getGoodsHistory(int current) async {

    String? shipperId = await UserIdManager.getUserID();
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));

    dio.get<String>(MyServiceUrl.header+'api/goods/goods/common/page?current=$current&size=20')
        .then((r) {
      setState(()   {
        print(r);

        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        String data = jsonMap['data'].toString();
        isLoading =false;
        if (code == "200") {
          if(pageNum==1) {
            dataList = jsonMap['data']['records'];
          }else{
            if(jsonMap['data']['records'].isNotEmpty){
              dataList.addAll(jsonMap['data']['records']);
            }else{
              pageNum=pageNum-1;
            }
          }

        } else {
          BrnToast.show(jsonMap['msg'].toString(), context);
        }

      });
    }).catchError((error) {
      BrnToast.show(error.toString(), context);
      print(error);
    });
  }

  void deleteBillAction(String id,String shipperId)async{
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(MyServiceUrl.header + 'api/goods/goods/common/delete',
      data:
        [
          {
            "id": id
          }
        ]
      ,
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          BrnToast.show("删除成功", context);
          getGoodsHistory(1);
        } else {

          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      BrnToast.show(error.toString(), context);
      ;
    });


  }


  Future _onRefresh() async {
    pageNum=1;
    getGoodsHistory(1);

  }
  Future _onLoad() async {
    if(dataList.length > 20*pageNum-1) {
      pageNum=pageNum+1;
      getGoodsHistory(pageNum);
    }

  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor:dataList.isNotEmpty? MyColors.backgreyColor:Colors.white,
      body:EasyRefresh(
        header:
        ClassicHeader(
          dragText: '下拉刷新',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '刷新成功',
          noMoreText: '暂无更多',
          failedText: '刷新失败',
          messageText: '刷新时间 %T',
        ),
        footer: ClassicFooter(
          dragText: '加载更多',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '加载成功',
          noMoreText: '暂无更多',
          failedText: '加载失败',
          messageText: '加载时间 %T',
        ),
        onRefresh: _onRefresh,
        onLoad:dataList.length > 20*pageNum-1?_onLoad:null,
        child: ListView(
            children: [
        dataList.isEmpty?Container(
        child: Center(
          child: BrnAbnormalStateWidget(
            img: Image.asset(
              'lib/Images/OrderList/发货中暂无货源.png',
              scale: 3.0,
            ),
            content: '暂无货源\n快去发货吧',
          ),
        ),
      )
          : Container(

        height: screenSize.height-200,
        child:
        ListView.builder(
          shrinkWrap:false,
            controller: _scrollController,
            itemCount: dataList.length,
          itemBuilder: (BuildContext context, int index) {
    if (index < dataList.length) {
            return GestureDetector(
                onTap:()async{
                final result=await  Navigator.push( context, FadeRoute(page:SourceDetails(
                    id: dataList[index]['id'],
                    shipperId: dataList[index]['shipperId'], checkPage: 1,
                  )));
              if(result!=null){
                getGoodsHistory(1);
              }

            },
            child:
              Container(
              padding: EdgeInsets.only(bottom: 8.h),
              margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      if(dataList[index]['description']==1)
                        BrnTagCustom(
                          tagText: "专票",
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      SizedBox(width: 4.w,),
                      // BrnTagCustom(
                      //   tagText: dataList[index]['status']==2?'成交下架':dataList[index]['status']==3?'取消下架':dataList[index]['status']==4?'删除下架':dataList[index]['status']==5?"超时下架":"异常下架",
                      //   fontSize: 14.sp,
                      //   fontWeight: FontWeight.w600,
                      //   backgroundColor: Color.fromRGBO(206, 206, 206, 1),
                      //   tagBorderRadius: BorderRadius.only(topRight: Radius.circular(10),bottomLeft: Radius.circular(10) ),
                      // ),
                    ],
                  ),
                  SizedBox(height: 4.h,),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SizedBox(width: 18.w,),
                      Column(
                        children: [
                          Image.asset("lib/Images/OrderList/装icon.png",width:13.w ,height:13.h,),
                          Image.asset("lib/Images/OrderList/垂直虚线.png",width:13.w ,height:15.h,),
                          if(dataList[index]['loadPlaceInfo'].length==2)
                            Column(
                              children: [
                                Image.asset("lib/Images/OrderList/装icon.png",width:13.w ,height:13.h,),
                                Image.asset("lib/Images/OrderList/垂直虚线.png",width:13.w ,height:15.h,),
                              ],
                            ),
                          if( dataList[index]['unloadPlaceInfo'].length==2)
                            Column(
                              children: [
                                Image.asset("lib/Images/OrderList/卸icon.png",width:13.w ,height:13.h,),
                                Image.asset("lib/Images/OrderList/垂直虚线.png",width:13.w ,height:15.h,),
                              ],
                            ),

                          Image.asset("lib/Images/OrderList/卸icon.png",width:13.w ,height:13.h,),
                        ],
                      ),
                      // SizedBox(width: 8.w,),

                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [

                          Row(
                            children: [
                              Text(dataList[index]["loadPlaceInfo"][0]["city"]+" "+dataList[index]["loadPlaceInfo"][0]["county"],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                            ],
                          ),

                          // Text(dataList[index]["loadPlaceInfo"][0]["detailedAddress"],style: TextStyle(color: Color.fromRGBO(154, 154, 154, 1),fontSize: 12.sp),),
                          SizedBox(height: 10.h,),
                          if(dataList[index]["loadPlaceInfo"].length==2)
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Text(dataList[index]["loadPlaceInfo"][1]["city"]+" "+dataList[index]["loadPlaceInfo"][1]["county"],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                                  ],
                                ),

                                // Text(dataList[index]["loadPlaceInfo"][1]["detailedAddress"],style: TextStyle(color: Color.fromRGBO(154, 154, 154, 1),fontSize: 12.sp),),
                                SizedBox(height:10.h,),
                              ],
                            ),

                          Row(
                            children: [
                              Text(dataList[index]["unloadPlaceInfo"][0]["city"]+" "+dataList[index]["unloadPlaceInfo"][0]["county"],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                              SizedBox(width: 8.w,),

                            ],
                          ),

                          // Text(dataList[index]["unloadPlaceInfo"][0]["detailedAddress"],style: TextStyle(color: Color.fromRGBO(154, 154, 154, 1),fontSize: 12.sp),),
                          if(dataList[index]["unloadPlaceInfo"].length==2)
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height:10.h,),
                                Row(
                                  children: [
                                    Text(dataList[index]["unloadPlaceInfo"][1]["city"]+" "+dataList[index]["unloadPlaceInfo"][1]["county"],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                                  ],
                                ),

                                // Text(dataList[index]["unloadPlaceInfo"][1]["detailedAddress"],style: TextStyle(color: Color.fromRGBO(154, 154, 154, 1),fontSize: 12.sp),),
                              ],
                            ),

                        ],

                      ),

                    ],
                  ),
                  SizedBox(height: 8.h,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(

                        children: [
                          Row(

                            children: [
                              SizedBox(width: 17.w,),
                              Text( dataList[index]["cargoInfo"][0]['cargoName'],style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                              if(dataList[index]["cargoInfo"][0]['cargoWeight']!=null)
                                Text( ","+dataList[index]["cargoInfo"][0]['cargoWeight'].toString()+"吨",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp)),
                              if(dataList[index]["cargoInfo"][0]['cargoVolume']!=null)
                                Text( ","+ dataList[index]["cargoInfo"][0]['cargoVolume'].toString()+"方",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp)),
                            ],

                          ),

                        ],
                      ),
                      if(dataList[index]["freight"]!=0)
                      Text((dataList[index]["freight"]).toString()+"元/趟"+"  ",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp,fontWeight: FontWeight.w600),),
                      if(dataList[index]["freight"]==0)
                        Text("电议"+"  ",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp,fontWeight: FontWeight.w600),),

                    ],
                  ),
                  Row(
                    children: [
                      SizedBox(width: 17.w,),
                      dataList[index]["vehicleLength"].contains(",")?
                      Text( dataList[index]["vehicleLength"].replaceAll(",", "米/")+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),):
                      Text( dataList[index]["vehicleLength"]+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                      if(dataList[index]["vehicleModel"]!=null)
                        dataList[index]["vehicleLength"].contains(",")?
                        Text("丨"+dataList[index]["vehicleModel"].replaceAll(",", "/"),style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),)
                            : Text("丨"+dataList[index]["vehicleModel"],style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                    ],
                  ),
                  Divider(height: 16.h,color: MyColors.backgreyColor,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          SizedBox(width: 15.w,),
                          Text(dataList[index]["createTime"].substring(5, 16),style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          GestureDetector(
                            child:  Container(
                                width: 50.w,
                                height: 25.h,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(30.0),
                                  border: Border.all(
                                    color: MyColors.themeColor,
                                    width: 1.0,
                                  ),
                                ),
                                child: Center(child: Text("编辑",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
                            ),
                            onTap: ()async{
                              final result =await   Navigator.push( context, FadeRoute(page:AddGoodsFirst(
                                dataMap:dataList[index], editType: 4,
                              )));
                              if(result !=null){
                                getGoodsHistory(1);
                              }
                            },
                          ),

                          SizedBox(width: 4.w,),
                          GestureDetector(
                            child:  Container(
                                width: 50.w,
                                height: 25.h,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(30.0),
                                  border: Border.all(
                                    color: MyColors.themeColor,
                                    width: 1.0,
                                  ),
                                ),
                                child: Center(child: Text("删除",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
                            ),
                            onTap: (){
                              deleteBillAction(dataList[index]['id'],"1");
                            },
                          ),

                          SizedBox(width: 4.w,),
                          GestureDetector(
                            child:  Container(
                                width: 80.w,
                                height: 25.h,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(30.0),
                                  border: Border.all(
                                    color: MyColors.themeColor,
                                    width: 1.0,
                                  ),
                                ),
                                child: Center(child: Text("再发一单",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
                            ),
                            onTap: (){
                              Navigator.push( context, FadeRoute(page:AddGoodsFirst(
                                dataMap:dataList[index], editType: 3,
                              )));
                            },
                          ),

                          SizedBox(width: 4.w,),

                        ],
                      ),
                    ],
                  )
                ],
              ),
              ),
            );
    }else{
      return _isLoading
          ? Padding(
        padding: EdgeInsets.all(8.0),
        child: Center(
          child: CircularProgressIndicator(),
        ),
      )
          : Container();
    }
          }
      ),
      ),
    ],),
      ),
    );
  }
}
